package br.com.bankai.koby.service.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import br.com.bankai.koby.repository.entity.Usuario;
import br.com.bankai.koby.repository.util.ConfiguracaoEnum;
import br.com.bankai.koby.service.exception.NoResultFoundException;
import br.com.bankai.koby.service.impl.ConfiguracaoService;
import br.com.graflogic.commonutil.util.email.EmailSender;
import br.com.graflogic.commonutil.util.email.EmailSenderRunnableWrapper;

/**
 * 
 * @author Leonardo
 *
 */
@Component
public class EmailService {

	private static final Logger LOGGER = LoggerFactory.getLogger(EmailService.class);

	private static final String USUARIO_PASSWORD_TAG = "#PASS";

	@Autowired
	private ConfiguracaoService configuracaoService;

	public void send(String toEmail, String subject, String body) {
		try {
			EmailSenderRunnableWrapper wrapper;

			wrapper = new EmailSenderRunnableWrapper(EmailSender.PROTOCOL_SMTP, configuracaoService.find(ConfiguracaoEnum.MAIL_SMTP_SERVER
					.getCodigo()), configuracaoService.find(ConfiguracaoEnum.MAIL_SMTP_SERVER_PORT.getCodigo()),
					configuracaoService.find(ConfiguracaoEnum.MAIL_USER.getCodigo()),
					configuracaoService.find(ConfiguracaoEnum.MAIL_FROM.getCodigo()), configuracaoService.find(ConfiguracaoEnum.MAIL_PASSWORD
							.getCodigo()), new String[] { toEmail }, null, subject, body, null, false, true, new Boolean(
							configuracaoService.find(ConfiguracaoEnum.MAIL_USE_SSL.getCodigo())), false, false, false);
			Thread thread = new Thread(wrapper);
			thread.start();
		} catch (NoResultFoundException e) {
			LOGGER.error("As configuracoes de envio de email nao estao configuradas", e);
		}
	}

	public void sendUsuarioPassword(Usuario usuario, String password) {
		try {
			send(usuario.getEmail().getValor(), configuracaoService.find(ConfiguracaoEnum.USUARIO_PASSWORD_MAIL_SUBJECT.getCodigo()),
					configuracaoService.find(ConfiguracaoEnum.USUARIO_PASSWORD_MAIL_BODY.getCodigo()).replace(USUARIO_PASSWORD_TAG, password));
		} catch (NoResultFoundException e) {
			LOGGER.error("As configuracoes do email de senha nao estao configuradas", e);
		}
	}
}